package com.tlxch.utils;

import com.tlxch.vo.AssessMsgvo;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 大学生心理状态评估工具类
 */
public class MentalHealthAssessor {

    public enum MentalIssueType {
        DEPRESSION, ANXIETY, STRESS, INSOMNIA, LONELINESS, LEARNING_DIFFICULTY
    }

    private static final Map<String, Double> KEYWORD_WEIGHTS = new HashMap<>();
    private static final Map<MentalIssueType, List<String>> ISSUE_KEYWORDS = new HashMap<>();
    private static final Map<MentalIssueType, String> ISSUE_SUGGESTIONS = new EnumMap<>(MentalIssueType.class);

    static {
        // 初始化关键词权重
        KEYWORD_WEIGHTS.put("抑郁", 0.8);
        KEYWORD_WEIGHTS.put("焦虑", 0.75);
        KEYWORD_WEIGHTS.put("压力", 0.7);
        KEYWORD_WEIGHTS.put("失眠", 0.65);
        KEYWORD_WEIGHTS.put("孤独", 0.6);
        KEYWORD_WEIGHTS.put("自杀", 2.0);
        KEYWORD_WEIGHTS.put("没意思", 0.5);
        KEYWORD_WEIGHTS.put("崩溃", 0.7);
        KEYWORD_WEIGHTS.put("不想活", 1.0);
        KEYWORD_WEIGHTS.put("睡不着", 0.6);
        KEYWORD_WEIGHTS.put("紧张", 0.6);
        KEYWORD_WEIGHTS.put("担心", 0.55);
        KEYWORD_WEIGHTS.put("害怕", 0.6);
        KEYWORD_WEIGHTS.put("绝望", 1.0);
        KEYWORD_WEIGHTS.put("上吊", 2.0);
        KEYWORD_WEIGHTS.put("跳楼", 2.0);
        KEYWORD_WEIGHTS.put("想死", 2.0);

        // 初始化问题分类关键词
        ISSUE_KEYWORDS.put(MentalIssueType.DEPRESSION, Arrays.asList("抑郁", "没意思", "绝望", "自杀", "不想活"));
        ISSUE_KEYWORDS.put(MentalIssueType.ANXIETY, Arrays.asList("焦虑", "紧张", "担心", "害怕", "崩溃"));
        ISSUE_KEYWORDS.put(MentalIssueType.STRESS, Arrays.asList("压力", "负担", "受不了", "喘不过气"));
        ISSUE_KEYWORDS.put(MentalIssueType.INSOMNIA, Arrays.asList("失眠", "睡不着", "早醒", "睡眠"));
        ISSUE_KEYWORDS.put(MentalIssueType.LONELINESS, Arrays.asList("孤独", "没人说话", "孤立", "不合群"));
        ISSUE_KEYWORDS.put(MentalIssueType.LEARNING_DIFFICULTY, Arrays.asList("学习压力", "考试", "挂科", "成绩"));

        // 初始化建议模板
        ISSUE_SUGGESTIONS.put(MentalIssueType.DEPRESSION, "建议每天进行15分钟阳光散步，记录积极事件，必要时寻求心理咨询。");
        ISSUE_SUGGESTIONS.put(MentalIssueType.ANXIETY, "尝试478呼吸法缓解紧张，将任务分解为小步骤逐步完成。");
        ISSUE_SUGGESTIONS.put(MentalIssueType.STRESS, "合理规划时间，设置休息间隔，避免过度劳累。");
        ISSUE_SUGGESTIONS.put(MentalIssueType.INSOMNIA, "建立固定作息，睡前1小时远离电子设备，尝试白噪音助眠。");
        ISSUE_SUGGESTIONS.put(MentalIssueType.LONELINESS, "主动参与校园活动或兴趣小组，增加社交互动频率。");
        ISSUE_SUGGESTIONS.put(MentalIssueType.LEARNING_DIFFICULTY, "制定学习计划，寻求同学或老师帮助，利用学习资源中心。");
    }

    public static AssessmentResult analyzeText(String text) {
        if (text == null || text.trim().isEmpty()) {
            return new AssessmentResult(1, 0.0, Collections.emptyMap());
        }

        String processedText = preprocessText(text);
        Map<String, Integer> keywordCounts = extractKeywords(processedText);
        double totalScore = calculateRiskScore(keywordCounts);
        int riskLevel = determineRiskLevel(totalScore);
        Map<MentalIssueType, Double> issueScores = classifyMentalIssues(keywordCounts);

        return new AssessmentResult(riskLevel, totalScore, issueScores);
    }

    private static String preprocessText(String text) {
        text = text.toLowerCase();
        return text.replaceAll("[\\p{Punct}\\s]+", "");
    }

    private static Map<String, Integer> extractKeywords(String text) {
        Map<String, Integer> keywordCounts = new HashMap<>();
        for (String keyword : KEYWORD_WEIGHTS.keySet()) {
            Pattern pattern = Pattern.compile(keyword);
            Matcher matcher = pattern.matcher(text);
            int count = 0;
            while (matcher.find()) {
                count++;
            }
            if (count > 0) {
                keywordCounts.put(keyword, count);
            }
        }
        return keywordCounts;
    }

    private static double calculateRiskScore(Map<String, Integer> keywordCounts) {
        double score = 0.0;
        for (Map.Entry<String, Integer> entry : keywordCounts.entrySet()) {
            score += KEYWORD_WEIGHTS.get(entry.getKey()) * Math.log(1 + entry.getValue());
        }
        return Math.min(10.0, score * 2);
    }

    private static int determineRiskLevel(double score) {
        if (score < 2.0) return 1;
        else if (score < 4.0) return 2;
        else if (score < 7.0) return 3;
        else return 4;
    }

    private static Map<MentalIssueType, Double> classifyMentalIssues(Map<String, Integer> keywordCounts) {
        Map<MentalIssueType, Double> issueScores = new EnumMap<>(MentalIssueType.class);
        for (MentalIssueType issueType : ISSUE_KEYWORDS.keySet()) {
            double score = 0.0;
            for (String keyword : ISSUE_KEYWORDS.get(issueType)) {
                if (keywordCounts.containsKey(keyword)) {
                    score += KEYWORD_WEIGHTS.get(keyword) * keywordCounts.get(keyword);
                }
            }
            if (score > 0) {
                issueScores.put(issueType, score);
            }
        }
        return issueScores;
    }

    public static class AssessmentResult {
        private final int riskLevel;
        private final double totalScore;
        private final Map<MentalIssueType, Double> issueScores;

        public AssessmentResult(int riskLevel, double totalScore, Map<MentalIssueType, Double> issueScores) {
            this.riskLevel = riskLevel;
            this.totalScore = totalScore;
            this.issueScores = issueScores;
        }

        public AssessMsgvo toAssessMsgvo() {
            AssessMsgvo assessMsgvo = new AssessMsgvo();
            assessMsgvo.setTsScore(totalScore);
            assessMsgvo.setTsLevel(riskLevel);

            List<String> contentList = new ArrayList<>();
            for (Map.Entry<MentalIssueType, Double> entry : issueScores.entrySet()) {
                MentalIssueType issueType = entry.getKey();
                String sugt = null;
                switch (issueType.name()) {
                    case "DEPRESSION":
                        sugt = "抑郁";
                        break;
                    case "ANXIETY":
                        sugt = "焦虑";
                        break;
                    case "STRESS":
                        sugt = "压力";
                        break;
                    case "INSOMNIA":
                        sugt = "失眠";
                        break;
                    case "LONELINESS":
                        sugt = "孤独";
                        break;
                    case "LEARNING_DIFFICULTY":
                        sugt = "学习困难";
                        break;
                }
                double score = entry.getValue();
                String suggestion = ISSUE_SUGGESTIONS.getOrDefault(issueType, "暂无针对性建议");

                String contentItem = String.format(
                        "%s评估：%.2f；建议：%s",
                        sugt,
                        score,
                        suggestion
                );

                contentList.add(contentItem);
            }

            assessMsgvo.setTsContent(contentList);
            return assessMsgvo;
        }

        // Getters
        public int getRiskLevel() { return riskLevel; }
        public double getTotalScore() { return totalScore; }
        public Map<MentalIssueType, Double> getIssueScores() { return issueScores; }
    }
}